package com.frame.framework.web.error;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import org.springframework.validation.BindingResult;

import com.frame.framework.web.error.enums.WebEnum;
import com.frame.framework.web.error.util.ErrorUtil;

import lombok.Data;



/**
 * @className ：WebError
 * @describe ：返回web端 数据封装类
 * {code：20000,message:"操作成功",data:{}}
 */
@Data
public class WebError implements Serializable {
	private static final long serialVersionUID = 1L;
	/**
	 * 返回状态码
	 */
	private int code;
	/**
	 * 返回状态信息
	 */
	private String msg;
	/**
	 * 返回的数据
	 */
	private Object data;

	public WebError(WebEnum webEnum) {
		this.code = webEnum.getCode();
		this.msg = webEnum.getMsg();
	}

	public WebError() {
		this.code = WebEnum.SUCCESS.getCode();
		this.msg = WebEnum.SUCCESS.getMsg();
	}

	public WebError(Integer code, String value) {
		this.code = code;
		this.msg = value;
	}
	
	public WebError(Object obejct) {
		
		this.code = WebEnum.SUCCESS.getCode();
		this.msg = WebEnum.SUCCESS.getMsg();
		this.data = obejct;
	}

	public WebError(String value) {
		
		this.code = WebEnum.ERROR.getCode();
		this.msg = WebEnum.ERROR.getMsg();
		this.data = value;
	}
	
	public WebError(WebEnum webEnum, Object obejct) {
		this.code = webEnum.getCode();
		this.msg = webEnum.getMsg();
		this.data = obejct;
	}

	Map<String, Object> map = new HashMap<>();
	public void putData(String key, Object data) {
		map.put(key, data);
		this.data = map;
	}

	public WebError(BindingResult result){
		super();
		this.code = 10000;
		this.msg = "验证错误";
		Map<String, String> errors = ErrorUtil.getErrors(result);
		for (String error : errors.keySet()) {
			this.putData(error, errors.get(error));
		}
	}
}
